package net.kts.placebook.oath;

import net.kts.main.KoreaTravelStoryActivity;
import net.kts.main.R;
import net.kts.placebook.session.UMISSession;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ActivityWebView extends Activity {
	
	private static final String TAG = "fs333";

    /**
     * Get these values after registering your oauth app at: https://foursquare.com/oauth/
     */
    public static final String CALLBACK_URL = "FourSqAndroid://foursquare";
    public static final String CLIENT_ID = "GKMOVLQ4ECJT2IAJAIMN03JNNOUYUS0KVJX15FFFDI4441IF";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pb_webview);
        
        String url =
            "https://foursquare.com/oauth2/authenticate" + 
                "?client_id=" + CLIENT_ID + 
                "&response_type=token" + 
                "&redirect_uri=" + CALLBACK_URL;
        
        // If authentication works, we'll get redirected to a url with a pattern like:  
        //
        //    http://YOUR_REGISTERED_REDIRECT_URI/#access_token=ACCESS_TOKEN
        //
        // We can override onPageStarted() in the web client and grab the token out.
        WebView webview = (WebView)findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            @Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
                String fragment = "#access_token=";
                int start = url.indexOf(fragment);
                if (start > -1) {
                    // You can use the accessToken for api calls now.
                    String getAccessToken = url.substring(start + fragment.length(), url.length());
        			
                    Log.v(TAG, "OAuth complete, token: [" + getAccessToken + "].");
                                        
                    // 토큰 세션에 저장
                    UMISSession.getInstance().setObjectByKey("accessToken", getAccessToken);
                    
                    finish();
                }
            }
        });

        webview.loadUrl(url);
        
    }
    
    @Override
    public void onBackPressed() {
      KoreaTravelStoryActivity.setCurrentTab(0);
      finish();
    }
}
